我需要創建一個Packet的Script來處理Packet的資訊,在伺服器或是客戶端進行封包傳輸前,需先將所有 Data type 轉成bytes,並將其儲存到 Buffer中。
一. 初始化
private List<byte> buffer;
private byte[] readableBuffer;
private int readPos;
/// <summary>Creates a new empty packet (without an ID).</summary>
public Packet()
{
buffer = new List<byte>(); // Initialize buffer
readPos = 0; // Set readPos to 0
}
/// <summary>Creates a new packet with a given ID. Used for sending.</summary>
/// <param name="_id">The packet ID.</param>
public Packet(int _id)
{
buffer = new List<byte>(); // Initialize buffer
readPos = 0; // Set readPos to 0
Write(_id); // Write packet id to the buffer
}
/// <summary>Creates a packet from which data can be read. Used for receiving.</summary>
/// <param name="_data">The bytes to add to the packet.</param>
public Packet(byte[] _data)
{
buffer = new List<byte>(); // Initialize buffer
readPos = 0; // Set readPos to 0
SetBytes(_data);
}
二. 撰寫封包資料
不同的資料型態都需要用BitConverter轉換成Bit來寫入封包 (不包括中文)。
public void Write(int _value)
{
buffer.AddRange(BitConverter.GetBytes(_value));
}
如果是中文字的話比較特別,要用到Encoding。
public void Write(string _value)
{
byte[] _bytes = Encoding.UTF8.GetBytes(_value);
Write(_bytes.Length); // Add the length of the string to the packet
buffer.AddRange(_bytes); // Add the string itself
}
三. 讀取封包資料
public int ReadInt(bool _moveReadPos = true)
{
if (buffer.Count > readPos)
{
// If there are unread bytes
int _value = BitConverter.ToInt32(readableBuffer, readPos); // Convert the bytes to an int
if (_moveReadPos)
{
// If _moveReadPos is true
readPos += 4; // Increase readPos by 4
}
return _value; // Return the int
}
else
{
throw new Exception("Could not read value of type 'int'!");
}
}